import { HttpException, Injectable } from '@nestjs/common';
import { LoginAuthDto } from './dto/login-auth.dto';
import { CreateAuthDto } from './dto/create-auth.dto';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from 'src/prisma/prisma.service';
import { CryptoService } from 'src/crypto/crypto.service';
import { UpdateAuthDto } from './dto/update-auth.dto';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly prismaService: PrismaService,
    private readonly cryptoService: CryptoService,
  ) {}
  async login(loginAuthDto: LoginAuthDto) {
    const user = await this.prismaService.user.findFirst({
      where: {
        username: loginAuthDto.username,
      },
    });

    if (!user) throw new HttpException('用户不存在', 401);

    if (loginAuthDto.username !== user.username)
      throw new HttpException('用户名错误', 401);
    const hashPassword = this.cryptoService.encrypt(loginAuthDto.password);
    if (hashPassword !== user.password)
      throw new HttpException('密码错误', 401);

    return {
      token: this.jwtService.sign({
        username: user.username,
        id: user.id,
      }),
    };
  }

  async register(createAuthDto: CreateAuthDto) {
    const res = await this.prismaService.user.findFirst({
      where: {
        username: createAuthDto.username,
      },
    });

    console.log(res);

    if (res) throw new HttpException('用户已存在', 401);

    try {
      await this.prismaService.user.create({
        data: {
          username: createAuthDto.username,
          password: this.cryptoService.encrypt(createAuthDto.password),
        },
      });
      return {
        code: 200,
        msg: '注册成功',
      };
    } catch (error) {
      throw new HttpException('注册失败', 401);
    }
  }

  async update(data: UpdateAuthDto, id: number) {
    if (data.confirmPassword !== data.newPassword) {
      throw new HttpException('两次密码不一致', 401);
    }

    try {
      const user = await this.prismaService.user.findFirst({
        where: {
          id,
        },
      });

      if (!this.cryptoService.verity(data.oldPassword, user.password)) {
        throw new HttpException('密码错误', 401);
      }

      await this.prismaService.user.update({
        where: {
          id,
        },
        data: {
          password: this.cryptoService.encrypt(data.newPassword),
        },
      });
    } catch (error) {
      throw new HttpException(error.response, 400);
    }
  }
}
